import { Button, Card, Input, List, Modal, Popover, Space, message } from "antd";
import { useEffect, useState } from "react";
import { getCollectionApi, getToken } from "./utils/client";
import CodeEditor from '@uiw/react-textarea-code-editor';
import Doc from "./components/Doc";
import { MoreOutlined } from "@ant-design/icons";


const PAGE_SIZE = 20;

export interface DocListProps {
    curClientId: string;
    curDatabase: string;
    curCollection: string;
}

function DocList(props: DocListProps) {

    const [tmpPattern, setTmpPattern] = useState("{}");
    const [pattern, setPattern] = useState("{}");
    const [recordList, setRecordList] = useState<string[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);
    const [showAddModal, setShowAddModal] = useState(false);
    const [newDoc, setNewDoc] = useState("{}");

    const loadRecordList = async () => {
        if (props.curClientId == "" || props.curDatabase == "" || props.curCollection == "") {
            return;
        }
        const client = getCollectionApi();
        const res = await client.collectionFindPost({
            collectionFindPostRequest: {
                token: getToken(),
                id: props.curClientId,
                database: props.curDatabase,
                collection: props.curCollection,
                query: pattern,
                offset: curPage * PAGE_SIZE,
                limit: PAGE_SIZE,
            },
        });
        setRecordList(res.docs ?? []);
        setTotalCount(res.count ?? 0);
    };

    const addDoc = async () => {
        let tmpDoc = newDoc;
        try {
            const obj = JSON.parse(tmpDoc);
            tmpDoc = JSON.stringify(obj);
        } catch (e) {
            console.log(e);
            message.error("错误的json格式")
            return;
        }
        const client = getCollectionApi();
        try {
            const idData = await client.collectionInsertPost({
                collectionInsertPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    database: props.curDatabase,
                    collection: props.curCollection,
                    doc: tmpDoc,
                },
            });
            message.info("增加成功");
            setShowAddModal(false);
            setCurPage(0);
            setPattern(idData);
            setTmpPattern(idData);
        } catch (e) {
            console.log(e);
            message.error("新增记录失败");
        }
    };

    useEffect(() => {
        if (props.curClientId != "" && props.curDatabase != "" && props.curCollection != "") {
            if (curPage == 0 && pattern == "{}") {
                loadRecordList();
            } else {
                setCurPage(0);
                setTmpPattern("{}");
                setPattern("{}");
            }
        }
    }, [props.curClientId, props.curDatabase, props.curCollection]);

    useEffect(() => {
        loadRecordList();
    }, [curPage, pattern])

    return (
        <Card title="记录列表" extra={
            <Space >
                <Input value={tmpPattern} onChange={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    if (e.target.value != "") {
                        setTmpPattern(e.target.value);
                    } else {
                        setTmpPattern("{}");
                    }
                }} style={{ width: "calc(100vw - 720px)" }}
                    disabled={props.curClientId == "" || props.curDatabase == "" || props.curCollection == ""}
                    allowClear
                />
                <Button type="primary"
                    style={{ marginRight: "20px" }}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        try {
                            JSON.parse(tmpPattern);
                            setPattern(tmpPattern);
                        } catch (e) {
                            console.log(e);
                            message.error("不是合法的json结构");
                        }
                    }} disabled={props.curClientId == "" || props.curDatabase == "" || props.curCollection == "" || tmpPattern == pattern}>搜索</Button>
                <Popover trigger="click" placement="bottom" content={
                    <div>
                        <Button type="link" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setNewDoc("{}");
                            setShowAddModal(true);
                        }} disabled={props.curClientId == "" || props.curDatabase == "" || props.curCollection == ""}>新增</Button>
                    </div>
                }>
                    <MoreOutlined />
                </Popover>


            </Space>
        } bordered={false} bodyStyle={{ height: "calc(100vh - 60px)", overflowY: "scroll", overflowX: "hidden" }}>
            <List dataSource={recordList} renderItem={(item, index) => (
                <List.Item key={index}>
                    <Doc curClientId={props.curClientId} curDatabase={props.curDatabase} curCollection={props.curCollection} doc={item}
                        onChange={() => loadRecordList()} />
                </List.Item>
            )} pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showSizeChanger: false }} />
            {showAddModal == true && (
                <Modal open title="增加记录" okText="增加"
                    bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "auto" }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowAddModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        addDoc();
                    }}>
                    <CodeEditor
                        value={newDoc}
                        language="json"
                        minHeight={200}
                        placeholder="请输入代码"
                        onChange={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                            setNewDoc(e.target.value);
                        }}
                        style={{
                            fontSize: 14,
                            backgroundColor: '#f5f5f5',
                        }}
                    />
                </Modal>
            )}
        </Card>
    );
}

export default DocList;